package com.bing.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * Created by kaibb on 16-1-13.
 */
public abstract class DBUtil {
    private static final String BACKUP_COMMAND = "mysqldump -u%s -p%s %s | gzip > %s.sql.gz ";
    private static final String RESTORE_COMMAND = "gunzip < %s.sql.gz | mysql -u%s -p%s %s ";
    private static final Logger LOGGER = LoggerFactory.getLogger(DBUtil.class);

    public static boolean backUp(String userName, String password, String dataBase, String path) {
        LOGGER.info("备份数据库:用户名:{}, 数据库:{}, 路径:{}", userName, dataBase, path);
        String[] cmd = {"/bin/bash", "-c", String.format(BACKUP_COMMAND, userName, password, dataBase, path)};
        return execCmd(cmd);
    }

    private static boolean execCmd(String[] cmd) {
        boolean flag = false;
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            int waitFor = process.waitFor();
            if (waitFor == 0) {
                LOGGER.info("执行命令{}成功", toString(cmd));
                flag = true;
            } else {
                InputStream errorStream = process.getErrorStream();
                byte[] buffer = new byte[errorStream.available()];
                errorStream.read(buffer);
                LOGGER.info("执行命令{}失败: {}", toString(cmd), new String(buffer));
            }
        } catch (Exception e) {
            LOGGER.error("执行命令失败", e);
        }
        return flag;
    }

    private static String toString(String[] array) {
        String str = null;
        for (String s : array) {
            str = s + " ";
        }
        return str;
    }

    public static boolean restore(String userName, String password,String dbName, String path) {
        LOGGER.info("还原数据库:用户名:{}, 数据库:{}, 路径:{}", userName,dbName, path);
        String[] cmd = {"/bin/bash", "-c", String.format(RESTORE_COMMAND, path, userName, password,dbName)};
        return execCmd(cmd);
    }
}
